package net.keebook.webapp.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.Query;

import net.keebook.webapp.entity.ItemGroup;


@Stateless
public class GroupDao extends Dao<ItemGroup> {
	@Override
	public void store(ItemGroup item) {
		super.store(item);
	}
	
	@Override
	public void update(ItemGroup item) {
		super.update(item);
	}
	
	@Override
	public ItemGroup get(Long id) {
		return super.get(id);
	}
	
	@Override
	public ItemGroup get(String id) {
		return super.get(id);
	}
	
	@Override
	public void delete(ItemGroup item) {
		getEntityManager().createQuery("DELETE FROM PasswordItem p WHERE p.group.id = :groupId").setParameter("groupId", item.getId()).executeUpdate();
		super.delete(item);
	}
	
	@SuppressWarnings("unchecked")
	public List<ItemGroup> getList(Long userId, Long keeBookId) {
		Query query = getEntityManager().createQuery("SELECT g FROM KeeBookAccess a, ItemGroup g WHERE g.keeBook.id = a.pk.keeBook.id AND a.pk.user.id = :userId AND a.pk.keeBook.id = :keeBookId ORDER BY g.title");
		query.setParameter("userId", userId);
		query.setParameter("keeBookId", keeBookId);
		return detachAll(query.getResultList());
	}
	
	public Long getGroupCount(Long userId, Long keeBookId) {
		Query query = getEntityManager().createQuery("SELECT COUNT(g.id) FROM KeeBookAccess a, ItemGroup g WHERE g.keeBook.id = a.pk.keeBook.id AND a.pk.user.id = :userId AND a.pk.keeBook.id = :keeBookId ORDER BY g.title");
		query.setParameter("userId", userId);
		query.setParameter("keeBookId", keeBookId);
		Long num = (Long)query.getSingleResult();
		return num;
	}
	
	public Boolean getHasGroups(Long userId, Long keeBookId) {
		return getGroupCount(userId, keeBookId) > 0;
	}
	
	public boolean canAccess(Long userId, Long groupId) {
		Query query = getEntityManager().createQuery("SELECT g FROM KeeBookAccess a, ItemGroup g WHERE g.keeBook.id = a.pk.keeBook.id AND a.pk.user.id = :userId AND g.id = :groupId");
		query.setParameter("userId", userId);
		query.setParameter("groupId", groupId);
		query.setMaxResults(1);
		return !query.getResultList().isEmpty();
	}
}
